package com.example.fbi_text.Acitivity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.fbi_text.R;
import com.example.fbi_text.bean.User;
import com.example.fbi_text.database.DBHelper;
import com.example.fbi_text.utils.SpUtils;
import com.example.fbi_text.views.MainActivity;

//登录功能
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText etUsername;
    private EditText etemail;
    private EditText etPassword;
    private Button btnLogin;
    private Button toRegister;
    private SpUtils mSpUtils;
    private boolean isPasswordVisible = false; // 标记密码是否可见

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mSpUtils = new SpUtils(this);
        int loginId=mSpUtils.getInt(SpUtils.LOGIN_KEY,-1);
        Log.d("LoginActivity","login id = "+loginId);
        //从桌面进入程序，如果已经登录，不显示登录界面，直接跳转到主界面。
        if (loginId >= 0) {
            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            return;
        }
        setContentView(R.layout.activity_login);
        etUsername=findViewById(R.id.etUsernameLogin);
        etemail=findViewById(R.id.etemailLogin);
        etPassword=findViewById(R.id.etPasswordLogin);
        btnLogin=findViewById(R.id.btnLogin);
        toRegister=findViewById(R.id.toRegister);
        btnLogin.setOnClickListener(this);
        toRegister.setOnClickListener(this);

        // 初始化密码图标（默认显示闭眼图标）
        etPassword.setCompoundDrawablesRelativeWithIntrinsicBounds(
                0, 0, R.drawable.ic_visibility_off, 0
        );

        // 设置密码图标的点击事件
        etPassword.setOnTouchListener((v, event) -> {
            if (event.getAction() == MotionEvent.ACTION_UP) {
                Drawable[] drawables = etPassword.getCompoundDrawables();
                Drawable drawableEnd = drawables[2]; // Index 2 is drawableEnd
                if (drawableEnd != null) {
                    // 计算图标点击区域
                    int clickableWidth = drawableEnd.getBounds().width() + etPassword.getPaddingRight();
                    if (event.getX() >= (etPassword.getWidth() - clickableWidth)) {
                        togglePasswordVisibility();
                        return true;
                    }
                }
            }
            return false;
        });
    }

    // 切换密码可见性
    private void togglePasswordVisibility() {
        if (isPasswordVisible) {
            // 隐藏密码
            etPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
            etPassword.setCompoundDrawablesRelativeWithIntrinsicBounds(0, 0, R.drawable.ic_visibility_off, 0);
        } else {
            // 显示密码
            etPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
            etPassword.setCompoundDrawablesRelativeWithIntrinsicBounds(0, 0, R.drawable.ic_visibility, 0);
        }
        isPasswordVisible = !isPasswordVisible;
        // 移动光标到末尾并强制刷新
        etPassword.setSelection(etPassword.getText().length());
        etPassword.setTypeface(etPassword.getTypeface()); // 修复输入类型不更新的问题
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id==R.id.toRegister){
            Intent intent=new Intent(LoginActivity.this,RegisterActivity.class);
            startActivity(intent);
        } else if (id == R.id.btnLogin) {
            String username=etUsername.getText().toString();
            String email=etemail.getText().toString();
            String password=etPassword.getText().toString();
            if (TextUtils.isEmpty(username) || TextUtils.isEmpty(email) ||TextUtils.isEmpty(password)) {
                //用户名、邮箱或密码没有输入，Toast显示
                Toast.makeText(this,"用户名、邮箱或密码不能为空",Toast.LENGTH_SHORT).show();
                return;
            }
            //数据库中查询用户名和密码都匹配的数据
            User user = DBHelper.getInstance(this).login(username,email,password);
            if (user == null) { //没有匹配的数据，登录失败，Toast提示。
                Toast.makeText(this, "登录失败", Toast.LENGTH_SHORT).show();
            } else {//登录成功跳转到主界面
                mSpUtils.putInt(SpUtils.LOGIN_KEY, user.getUser_id());//记录当前登录用户的id
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        }
    }
}